<template>
  <a-modal v-model:visible="visible" :title="title" :maskClosable="false" :footer="null">
    <a-form :label-col="labelCol">
      <a-form-item label="部门名称" v-bind="validateInfos.name">
        <a-input v-model:value="formState.name" placeholder="部门名称" />
      </a-form-item>
      <a-row>
        <a-col :md="12" :xs="24">
          <a-form-item label="部门排序" v-bind="validateInfos.deptSort">
            <a-input-number v-model:value="formState.deptSort" :min="0" :max="999" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :xs="24">
          <a-form-item label="状态">
            <a-radio-group v-model:value="formState.enabled">
              <a-radio v-for="item in dictOptions" :key="item.id" :value="item.value">{{
                item.label
              }}</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item label="顶级部门">
        <a-radio-group v-model:value="formState.isTop" button-style="solid">
          <a-radio-button value="1">是</a-radio-button>
          <a-radio-button value="0">否</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="上级部门" v-if="formState.isTop === '0'">
        <a-tree-select
          v-model:value="formState.pid"
          tree-data-simple-mode
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          :tree-data="categoryOptions"
          placeholder="选择上级类目"
          :load-data="onLoadData"
          :field-names="replaceFields"
        />
      </a-form-item>

      <a-form-item style="margin-bottom: 0px; margin-top: 40px; text-align: right">
        <a-button type="primary" @click.prevent="onSubmit">确认</a-button>
        <a-button style="margin-left: 10px" @click="resetFields">重置</a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts">
  import { defineComponent, toRaw, reactive, ref, watch } from 'vue';
  import { Form, notification, message } from 'ant-design-vue';
  import { getDeptsApi, getDeptSuperiorApi, addDeptApi, editDeptApi } from '/@/api/dept';
  import { reload, buildDepts } from './index';
  import { getDictDetailApi } from '/@/api/dictDetail';

  const replaceFields = {
    children: 'children',
    title: 'name',
    value: 'id',
    isLeaf: 'leaf',
  };

  const formState = reactive({
    id: null,
    name: '',
    isTop: '1',
    subCount: 0,
    pid: null,
    deptSort: 999,
    enabled: 'true',
  });
  const rulesRef = reactive({
    name: [
      {
        required: true,
        message: '请输入名称',
      },
    ],
    deptSort: [
      {
        required: true,
        message: '请输入序号',
        type: 'number',
      },
    ],
  });
  const useForm = Form.useForm;
  const { resetFields, validate, validateInfos } = useForm(formState, rulesRef);

  export default defineComponent({
    setup() {
      const visible = ref<boolean>(false);
      const title = ref<string>('');
      watch(visible, (newVal, _oldVal) => {
        if (!newVal) {
          resetFields();
        }
      });

      const categoryOptions = ref<any>([]);
      const getDepts = async (params: { pid?: number }) => {
        const res = await getDeptsApi({ ...params, enabled: true });
        const depts = res?.content?.map(function (obj) {
          if (obj.hasChildren) {
            obj.children = null;
          }
          return obj;
        });

        return depts;
      };

      const getSupDepts = async (id: number) => {
        const res = await getDeptSuperiorApi([id]);
        const data = res?.content;
        buildDepts(data);
        categoryOptions.value = data;
      };

      const dictOptions = ref([]);
      const open = async (isAdd: boolean, record) => {
        if (isAdd) {
          title.value = '新增部门';
          categoryOptions.value = await getDepts({});
        } else {
          title.value = '编辑部门';
          formState.id = record.id;
          formState.name = record.name;
          formState.deptSort = record.deptSort;
          formState.enabled = String(record.enabled);
          formState.pid = record.pid;
          if (!!formState.pid) {
            formState.isTop = '0';
          }
          getSupDepts(record.id);
        }
        //获取字典数据
        const resDict = await getDictDetailApi('dept_status');
        dictOptions.value = resDict?.content;
        visible.value = true;
      };

      const onLoadData = (treeNode: any) => {
        return new Promise((resolve: (value?: unknown) => void) => {
          if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
            resolve();
            return;
          }
          setTimeout(async () => {
            const id = treeNode.dataRef.id;
            const data = categoryOptions.value;
            let response = await getDepts({
              pid: id,
            });
            //获取到的子节点
            const children = response ?? [];
            const dataMap = (items: Array<any>) => {
              items.find((item) => {
                if (item.id === id) {
                  //找到当前要展开的节点
                  item.children = children;
                  return items;
                }
                if (item.children && item.children.length > 0) {
                  dataMap(item.children);
                }
              });
            };
            dataMap(data || []);
            categoryOptions.value = data;
            resolve(true);
          }, 200);
        });
      };

      const onSubmit = (_e: MouseEvent) => {
        validate()
          .then(async () => {
            const item = toRaw(formState);
            if (item.pid !== null && item.pid === item.id) {
              message.warning('上级部门不能为空或自己');
              return;
            }
            if (item.isTop === '1') {
              item.pid = null;
            }

            try {
              if (!!formState.id) {
                await editDeptApi({
                  ...item,
                });
                notification['success']({
                  message: '编辑部门成功',
                  duration: 3,
                });
              } else {
                await addDeptApi({
                  ...item,
                });
                notification['success']({
                  message: '新增部门成功',
                  duration: 3,
                });
              }
              visible.value = false;
              reload.value = !reload.value;
            } catch (error) {}
          })
          .catch((err) => {
            console.log('error', err);
          });
      };

      return {
        open,
        visible,
        title,
        onSubmit,
        labelCol: { style: { width: '80px' } },
        wrapperCol: { span: 14 },
        validateInfos,
        resetFields,
        formState,
        categoryOptions,
        onLoadData,
        replaceFields,
        dictOptions,
      };
    },
  });
</script>
